<!-- 店铺商品列表 @zjf-2020-12-30 -->
<template>
  <div class="self_background">
    <StoreHeaderCat ref="headercat" @sendGoodsName="sendGoodsName"/>
    <div
      class="sld_store_goods_list clearfix"
      :class="{ skeleton_sld_store_goods_list: firstLoading }"
    >
      <!-- 左侧分类 start -->
      <div
        class="left_cat_wrap"
        v-show="firstLoading ? true : storeData.cat.length"
      >
        <template
          v-for="(item, index) in firstLoading
            ? skeletonData.category
            : storeData.cat"
          :key="index"
        >
          <dl
            :class="{
              store_cat_item: true,
              on: !(item.openFlag != undefined && !item.openFlag),
            }"
          >
            <dt class="grade_one_cat">
                <router-link
                    :to="'/store/goods/'+ calcProductName(storeName) +'_v-'+ vid + '_c-' + item.innerLabelId"
              >
                {{ item.innerLabelName }}
              </router-link>
              <i
                v-if="item.children.length"
                class="more"
                @click="toggleOpenFlag(index)"
              ></i>
            </dt>
            <dd
              v-if="
                item.children.length &&
                !(item.openFlag != undefined && !item.openFlag)
              "
            >
              <router-link
                v-for="(item_child, index_child) in item.children"
                :key="index_child"
                :to="'/store/goods/'+ calcProductName(storeName) +'_v-'+ vid + '_c-' + item_child.innerLabelId"
              >
                {{ item_child.innerLabelName }}
              </router-link>
            </dd>
          </dl>
        </template>
      </div>
      <!-- 左侧分类 end -->

      <!-- 右侧商品 start -->
      <div
        :class="{
          right_goods_wrap: true,
          fr: storeData.cat.length,
          no_cate_goods_wrap: !storeData.cat.length,
        }"
      >
        <div class="store_goods_search_nav">
          <span :class="{ active: sort == 0 }" >{{
            L["综合"]
          }}</span>

          <div class="sld_store_goods_total_num">
            {{ L["共"] }} {{ storeData.goods.pagination.total
            }} {{ L["件相关商品"] }}
          </div>
        </div>
        <ul class="sld_store_goods_list_wrap">
          <li
            v-for="(item, index) in firstLoading
              ? skeletonData.goods
              : storeData.goods.list"
            :key="index"
          >
            <div class="sld_goods_img">
              <router-link
                target="_blank"
                :to="'/goods/detail/'+ calcProductName(item.goodsDefaultName) +'_'+ item.defaultProductId"
              >
                <img :src="item.goodsImage" style="display: block" />
              </router-link>
            </div>
            <div class="sld_goods_name_wrap">
              <router-link
                target="_blank"
                :to="'/goods/detail/'+ calcProductName(item.goodsDefaultName) +'_'+ item.defaultProductId"
                :title="item.goodsName"
                v-html="item.goodsName"
                class="sld_goods_name"
              >
              </router-link>
            </div>

            <p class="clearfix">
              <span class="sld_goods_price fl"
                ><em>{{
                  item.goodsMoney == null ? "Contact us to give you an individual quote" : item.goodsMoney
                }}</em></span
              >
            </p>

            <div class="promotion_tag">
              <template v-if="item.activityList && item.activityList.length">
                <div style="display: flex">
                  <div
                    v-for="(item_activity, index_activity) in item.activityList"
                    :key="index_activity"
                  >
                    <span class="promotion_tag_text">{{
                      item_activity.promotionName
                    }}</span>
                  </div>
                </div>
              </template>
              <button
                class="sld_collect_wrap fr flex_row_center_center"
                :class="{ collect_active: item.isFollowGoods }"
                @click="collect(item.defaultProductId, item.isFollowGoods)"
              >
                <img
                  src="/goods/collection.png"
                  alt=""
                  v-show="item.isFollowGoods == true"
                  style="width: 20px; height: 20px"
                />
                <img
                  src="/goods/no_collection.png"
                  alt=""
                  v-show="item.isFollowGoods == false"
                  style="width: 20px; height: 20px"
                />
                {{ L["收藏"] }}
              </button>
            </div>
          </li>
        </ul>
        <!-- 分页 start -->
        <div class="flex_row_center_center sld_pagination">
          <el-pagination
            @current-change="handleCurrentChange"
            v-model:currentPage.sync="pagitionCurrent"
            :page-size="storeData.goods.pagination.pageSize"
            layout="prev, pager, next"
            :total="storeData.goods.pagination.total"
            :hide-on-single-page="true"
          >
          </el-pagination>
        </div>
        <!-- 分页 end -->
      </div>
      <!-- 右侧商品 end -->
      <SldLoginModal
        v-if="loginModalVisibleFlag"
        @closeLoingModal="closeLoingModal"
      />

      <!-- 空页面 start-->
      <SldCommonEmpty
        v-if="!firstLoading && !storeData.goods.list.length"
        totalWidth="979"
        totalHeight="700"
        paddingTop="200"
      />
      <!-- 空页面 end-->
    </div>
  </div>
</template>

<script setup>
import { ElMessage, ElPagination } from "element-plus";
// import { lang_zn } from "@/assets/language/zh";
import { getCurLanguage } from '@/composables/common.js';
import { useFiltersStore } from "@/store/filter.js";

const filtersStore = useFiltersStore();
const proxy = getCurrentInstance();
const route = useRoute();
// const L = lang_zn;
const L = getCurLanguage();
const firstLoading = ref(true); //是否第一次加载
const router = useRouter();
const storeData = reactive({ cat: [], goods: { list: [], pagination: {} } }); //店铺数据，cat：店铺分类，goods：店铺商品列表
const sort = ref(0); //0:默认/综合；1、销量从高到底；3、价格从低到高；4、价格从高到低；5、人气从高到低
const headercat = ref(null); //获取dom的ref,名字同名
const loginModalVisibleFlag = ref(false); //登录弹框是否显示，默认不显示
const skeletonData = reactive({ category: [], goods: [] });
const SEOinfo = reactive({
  seoTitle: "Products",
  seoDesc: "",
  seoKeywords: "",
});
//动态页面数据
const vid = ref();
const currentPage = ref(1); //分页——当前页
const categoryId = ref(); //分类id
const keyword = ref(); //搜索关键词
const pagitionCurrent = ref(1)
const storeName = ref('')

//接收店铺名称
const sendGoodsName = (val) => {
  storeName.value = val
}

const clacRouteParams = () => {
  if (calcUrlPagination(route.path)) {
    currentPage.value = calcUrlPagination(route.path)
  }
  if (calcUrlShopId(route.path)) {
    vid.value = calcUrlShopId(route.path)
  }
  if (calcUrlCatId(route.path)) {
    categoryId.value = calcUrlCatId(route.path);
  }
  if (calcUrlKeywords(route.path)) {
    keyword.value = calcUrlKeywords(route.path);
  }
  proxy.refs.headercat.setVid(calcUrlShopId(route.path));
  getStoreGoodsList();
  getStoreCatData();
};

watch(
  () => currentPage.value,
  (nv, ov) => {
    if (nv != ov) {
      pagitionCurrent.value = Number(nv)
    }
  }
);
//根据切换数据，改变SEO
const setSEO = () => {
  if (categoryId.value == "") {
    useHead({
      title: "Products",
      meta: [
        {
          name: "description",
          content: "Products",
        },
        {
          name: "keywords",
          content: "Products",
        },
      ],
    });
    return;
  }
  for (let i in storeData.cat) {
    if (storeData.cat[i].innerLabelId == categoryId.value) {
      SEOinfo.seoTitle = storeData.cat[i].seoInfo.seoTitle;
      SEOinfo.seoDesc = storeData.cat[i].seoInfo.seoDesc;
      SEOinfo.seoKeywords = storeData.cat[i].seoInfo.seoKeywords;
      break;
    } else {
      for (let j in storeData.cat[i].children) {
        if (storeData.cat[i].children[j].innerLabelId == categoryId.value) {
          SEOinfo.seoTitle = storeData.cat[i].children[j].seoInfo.seoTitle;
          SEOinfo.seoDesc = storeData.cat[i].children[j].seoInfo.seoDesc;
          SEOinfo.seoKeywords =
            storeData.cat[i].children[j].seoInfo.seoKeywords;
        }
      }
    }
  }
  useHead({
    title: SEOinfo.seoTitle,
    meta: [
      {
        name: "description",
        content: SEOinfo.seoDesc,
      },
      {
        name: "keywords",
        content: SEOinfo.seoKeywords,
      },
    ],
  });
};

const initSkeletonData = () => {
  for (let i = 0; i < 5; i++) {
    skeletonData.category.push({
      innerLabelId: "",
      innerLabelName: "",
      openFlag: true,
      children: [
        { innerLabelId: "", innerLabelName: "0" },
        { innerLabelId: "", innerLabelName: "0" },
        { innerLabelId: "", innerLabelName: "0" },
      ],
    });
  }
  for (let i = 0; i < 8; i++) {
    skeletonData.goods.push({
      defaultProductId: "",
      goodsImage: "",
      goodsPrice: "",
      saleNum: "",
      activityList: [],
      isFollowGoods: false,
    });
  }
};

//获取店铺分类数据
const getStoreCatData = async () => {
  const { data: value } = await useFetchRaw(
    apiUrl + "v3/seller/front/store/storeCategory?storeId=" + vid.value
  );
  const res = value._rawValue;
  if (res.state == 200) {
    storeData.cat = res.data;
  }
  setSEO();
};


//获取店铺商品列表
const getStoreGoodsList = async () => {
  let param = {};
  let key = "";
  param.storeId = vid.value;
  key += vid;
  param.current = currentPage.value;
  key += currentPage.value;

  if (categoryId.value) {
    param.storeInnerLabelId = categoryId.value;
    key += categoryId.value;
  }
  if (keyword.value) {
    param.keyword = keyword.value;
    key += keyword.value;
  }
  // param.pageSize = 6;
  const { data: value, pending: pending } = await useFetchRaw(
    apiUrl + "v3/goods/front/goods/goodsList",
    { params: param, key: key, headers:{Authorization:'Bearer ' + filtersStore.getToken }}
  );
  const res = value._rawValue;
  if (!pending._rawValue) {
    firstLoading.value = false;
  }
  if (res.state == 200) {
    storeData.goods = res.data;
  }
};

const toggleOpenFlag = (key) => {
  storeData.cat[key].openFlag =
    storeData.cat[key].openFlag != undefined
      ? !storeData.cat[key].openFlag
      : false;
};
//分页切换/前往指定页面
const handleCurrentChange = (val) => {
  currentPage.value = val;
  let path = "/store/goods/"+ calcProductName(storeName.value)+"_v-"+ vid.value +"_p-" + val
  if(keyword.value && !categoryId.value){
    path += "_k-" +keyword.value
  }
  else if(keyword.value && categoryId.value){
    path += "_c-" + categoryId.value  +"_k-" +keyword.value
  }
  else if(!keyword.value && categoryId.value){
    path += "_c-" + categoryId.value
  }
  router.push({
    path: path
  });

};

watch(categoryId, (newValue, oldValue) => {
  if (newValue != oldValue) {
    setSEO();
  }
});


//收藏功能
const collect = (defaultProductId, isFollowGoods) => {
  if (filtersStore.getLoginFlag) {
    //收藏功能
    let params = {
      productIds: defaultProductId,
      isCollect: !isFollowGoods,
    };
    post("v3/member/front/followProduct/edit", params).then((res) => {
      if (res.state == 200) {
        ElMessage.success(res.msg);
        storeData.goods.list.map((storeGoodsItem) => {
          if (storeGoodsItem.defaultProductId == defaultProductId) {
            storeGoodsItem.isFollowGoods = !storeGoodsItem.isFollowGoods;
          }
        });
      } else {
        ElMessage.error(res.msg);
      }
    });
  } else {
    //未登录的话提示登录
    loginModalVisibleFlag.value = true;
  }
};
const closeLoingModal = () => {
  loginModalVisibleFlag.value = false;
};

onMounted(() => {
  setTimeout(() => {
    sldStatEvent({ behaviorType: 'spv', storeId: vid.value ,pageUrl: defaultUrl + router.currentRoute.value.path, referrerPageUrl: apiUrl });
    }, 3000)
  initSkeletonData();
  nextTick(() => {
    clacRouteParams();
  });
});
</script>
<style lang="scss" scoped>
@import "@/assets/style/store/goodsList.scss";
@import "@/assets/style/theme.scss";

.el-pager li.active {
  color: $colorMain;
  cursor: default;
}

.el-pager li:hover {
  color: $colorMain;
}

.sld_pagination {
  margin: 20px 0 20px 0;
}

.store_goods_search_nav {
  cursor: pointer;
}
</style>
